// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.neuronbit.businessflow.intellij.editor.swing.editor;

import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.PropertiesUtilBase;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ModuleRootEvent;
import com.intellij.openapi.roots.ModuleRootListener;
import com.intellij.openapi.util.Pair;
import com.intellij.uiDesigner.lw.StringDescriptor;
import com.intellij.util.SlowOperations;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Locale;
import java.util.Map;


/**
 * The type String descriptor manager.
 */
public final class StringDescriptorManager {
  private Module myModule;
  private final Map<Pair<Locale, String>, PropertiesFile> myPropertiesFileCache = ContainerUtil.createSoftValueMap();

    /**
     * Instantiates a new String descriptor manager.
     *
     * @param module the module
     */
    public StringDescriptorManager(@NotNull Module module) {
    myModule = module;
    module.getProject().getMessageBus().connect().subscribe(ModuleRootListener.TOPIC, new ModuleRootListener() {
      @Override
      public void rootsChanged(@NotNull ModuleRootEvent event) {
        synchronized(myPropertiesFileCache) {
          myPropertiesFileCache.clear();
        }
      }
    });
  }

    /**
     * Gets instance.
     *
     * @param module the module
     * @return the instance
     */
    public static StringDescriptorManager getInstance(Module module) {
    StringDescriptorManager service = module.getService(StringDescriptorManager.class);
    if (service != null) {
      service.myModule = module;
    }
    return service;
  }

    /**
     * Resolve string.
     *
     * @param component  the component
     * @param descriptor the descriptor
     * @return the string
     */
    @Nullable public String resolve(@NotNull RadComponent component, @Nullable StringDescriptor descriptor) {
    RadRootContainer root = (RadRootContainer) FormEditingUtil.getRoot(component);
    Locale locale = (root != null) ? root.getStringDescriptorLocale() : null;
    return resolve(descriptor, locale);
  }

    /**
     * Resolve string.
     *
     * @param descriptor the descriptor
     * @param locale     the locale
     * @return the string
     */
    @Nullable public String resolve(@Nullable StringDescriptor descriptor, @Nullable Locale locale) {
    if (descriptor == null) {
      return null;
    }

    if (descriptor.getValue() != null) {
      return descriptor.getValue();
    }

    IProperty prop = resolveToProperty(descriptor, locale);
    if (prop != null) {
      final String value = prop.getUnescapedValue();
      if (value != null) {
        return value;
      }
    }
    // We have to return surrogate string in case if propFile name is invalid or bundle doesn't have specified key
    return "[" + descriptor.getKey() + " / " + descriptor.getBundleName() + "]";
  }

    /**
     * Resolve to property property.
     *
     * @param descriptor the descriptor
     * @param locale     the locale
     * @return the property
     */
    public IProperty resolveToProperty(@NotNull StringDescriptor descriptor, @Nullable Locale locale) {
    String propFileName = descriptor.getDottedBundleName();
    Pair<Locale, String> cacheKey = Pair.create(locale, propFileName);
    PropertiesFile propertiesFile;
    synchronized (myPropertiesFileCache) {
      propertiesFile = myPropertiesFileCache.get(cacheKey);
    }
    if (propertiesFile == null || !propertiesFile.getContainingFile().isValid()) {
      try (AccessToken ignore = SlowOperations.knownIssue("IDEA-307701, EA-723514")) {
        propertiesFile = PropertiesUtilBase.getPropertiesFile(propFileName, myModule, locale);
        synchronized (myPropertiesFileCache) {
          if (propertiesFile != null) {
            myPropertiesFileCache.put(cacheKey, propertiesFile);
          }
        }
      }
    }

    if (propertiesFile != null) {
      try (AccessToken ignore = SlowOperations.knownIssue("IDEA-307701, EA-254373")) {
        final IProperty propertyByKey = propertiesFile.findPropertyByKey(descriptor.getKey());
        if (propertyByKey != null) {
          return propertyByKey;
        }
      }
    }
    return null;
  }
}
